package lol.clann.minecraft.springboot.api.model;

import java.util.function.Supplier;

/**
 * 线程安全的懒加载
 *
 * @author pyz
 * @date 2019/5/18 1:51 PM
 */
public class LazyField<T> {
    private T t;
    private boolean init = false;
    private final Supplier<T> getter;

    private LazyField(Supplier<T> getter) {
        this.getter = getter;
    }

    public static <T> LazyField<T> of(Supplier<T> getter) {
        return new LazyField<>(getter);
    }

    public T get() {
        if (init) {
            return t;
        }
        synchronized (this) {
            if (init) {
                return t;
            }
            init = true;
            t = getter.get();
        }
        return t;
    }
}
